import { cityApi } from "@/api/city.js";

const cityModule = {
  // 命名空间，让getters，mutations，actions都在模块下
  namespaced: true,
  state() {
    return {
      cityName: localStorage.getItem("name") || "全国",
      cityId: localStorage.getItem("id") || 0,
      // 城市列表
      cityList: [],
    };
  },
  getters: {
    hotCity(state) {
      return state.cityList[0];
    },
    otherCity(state) {
      return state.cityList.slice(1);
    },
  },
  mutations: {
    changeName(state, payload) {
      state.cityName = payload.name;
      state.cityId = payload.cityId;
    },
    // 同步改变城市列表
    getCity(state, payload) {
      state.cityList = payload.result;
    },
  },
  actions: {
    // 城市列表的请求
    async asyncGetCity({ commit }) {
      const res = await cityApi();
      commit("getCity", res);
    },
  },
};

export default cityModule;
